<template>
  <div class="add">
    <el-form ref="form" :model="form" label-width="8rem">
      <el-form-item>
        <span slot="label">员工姓名<span class="red">*</span></span>
        <el-input v-model="form.userName" placeholder="请输入员工姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <span slot="label">手机号<span class="red">*</span></span>
        <el-input v-model="form.telephone" placeholder="请输入11位手机号" ></el-input>
      </el-form-item>
      <el-form-item>
        <span slot="label">员工所在部门<span class="red">*</span></span>
        <el-select v-model="form.depCode" placeholder="请选择部门"
                   style="width:38%">
          <el-option
            v-for="item in departmentList"
            :key="item.depCode"
            :label="item.depName"
            :value="item.depCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="员工职位">
        <el-input v-model="form.userPos" placeholder="请输入员工职位"></el-input>
      </el-form-item>
      <el-form-item>
        <span slot="label">是否可借用设备<span class="red">*</span></span>
        <el-select v-model="form.userStatus" placeholder="请选择"
                   style="width:38%">
          <el-option
            v-for="item in stateList"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="头像上传:">
        <el-upload
          class="upload-demo"
          ref="upload"
          accept=".png,.jpg,.jpeg"
          :on-change="handleChange"
          :action="uploadUrl"
          :limit="1"
          :show-file-list="true"
          :auto-upload="false"
        >
          <el-button type="primary" slot="trigger">选取文件</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="uploadSuccess==false">确认上传</el-button>
          <i class="el-icon-success" style="color: green" v-else>头像已上传,待保存</i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateData">保存</el-button>
        <el-button type="default" @click="back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import $ from "@/api/departStaff";

  export default {
    data() {
      return {
        form: {
          userId: "",
          depCode: "",
          telephone: "",
          userName: "",
          userPhoto: "",
          userPos: "",
          userStatus: undefined,
        },
        uploadSuccess: false,
        uploadUrl: '',
        uploadfile: "",
        updatefile: "",
        listLoading: true,

        departmentList: [],
        stateList: [
          {
            key: 1,
            value: "可借用"
          },
          {
            key: 2,
            value: "不可借用"
          }
        ]
      };
    },
    created() {
      this.form.userId = this.$route.query.id
      this.fetchData()
      // 部门列表
      $.tbDmReturnList().then(res => {
        this.departmentList = res.data
        // console.log(res.data)
      })
    },
    methods: {
      fetchData() {
        $.tbUserGetById({userId: this.$route.query.id}).then(res => {
          // console.log(res.data)
          this.form = res.data
          if (res.data.userPhoto != "" && res.data.userPhoto != null) {
            this.uploadSuccess = true
          }
        })
      },
      handleChange(file) {
        this.uploadfile = file
        this.uploadSuccess = false
      },
      handleSubmit() {

        if (this.uploadfile == "") {
          this.$message({
            message: "请先选择图片",
            type: 'error'
          })
          return
        }
        this.listLoading = true;
        let formData = new FormData()
        let data = JSON.stringify(this.form)
        formData.append('file', this.uploadfile.raw);
        // formData.append("tbUser", new Blob([data], {type: "application/json"}));
        // console.log(this.uploadfile)
        $.tbUserImg(formData).then(res => {
          if (res.success) {
            this.$refs.upload.clearFiles()
            // console.log(res.data)
            this.form.userPhoto = res.data
            this.$message({
              message: "上传成功",
              type: 'success'
            })
            this.uploadSuccess = true
          }
        })
      },
      updateData() {
        if (!this.validate()) return;
        $.tbUserUpdate(this.form).then(response => {
          if (response.data == "更新成功") {
            this.$message({
              type: "success",
              message: "更新成功"
            });
            this.$router.replace('index')
          } else {
            this.$message({
              type: "error",
              message: "该手机号已存在"
            });
          }

          this.$router.replace('index')
        });
      },
      validate() {
        let error = "";
        if (!/^([\u4e00-\u9fa5]{2,20}|[a-zA-Z.\s]{2,20})$/.test(this.form.userName)) {
          error = "姓名长度必须为2-20个字符\n";
        } else if (!/^1[0-9]{10}$/.test(this.form.telephone)) {
          error = "请输入正确的手机号\n";
          this.form.telephone = ""
        } else if (this.form.depCode == "" || this.form.depCode == null) {
          error = "请选择部门\n"
        } else if (this.form.userStatus == "" || this.form.userStatus == null) {
          error = "请选择是否可借用设备\n"
        }
        if (error) {
          this.$message({
            message: error,
            type: "error"
          });
          return false;
        }
        return true;
      },
      back() {
        this.$router.replace('index')
      }
    }
  };
</script>
<style scoped>
  .add {
    padding: 1rem;
  }

  .red {
    color: red;
    font-size: 1.5rem;

    vertical-align: middle;
  }
</style>
